<template>
  <div class="tem_page">
    <el-card class="box-card">
      <div slot="header">
        <h3>线索商品-编辑</h3>
      </div>
      <el-row type="flex" justify="end">
        <el-button @click="hanldeGoBack">返回</el-button>
        <el-button :loading="btnLoadings.export" @click="handleExportTemplate">导出</el-button>
        <el-upload
          class="import-file"
          ref="bacthUpload"
          :action="`${uploadBaseURL}sysback/product/collect/importProductCollectTemplate`"
          accept=".xls, .xlsx"
          :before-upload="beforeFileUpload"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :show-file-list="false"
          :data="uploadData"
        >
          <el-button :loading="btnLoadings.import" @click="handleImport">导入</el-button>
        </el-upload>
        <el-button type="primary" :loading="submitBtnLoading" @click="handleSubmitAction">提交</el-button>
      </el-row>
      <el-divider />
      <el-row type="flex" justify="end" class="operating">
        <el-select
          v-model="formData.productNameType"
          placeholder="是否自定义商品名称"
          @change="handleProductNameTypeSelect"
        >
          <el-option
            v-for="item in PRODUCT_NAME_TYPE"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-select
          :disabled="!selectedProductIds.length"
          v-model="formData.salePlatCodes"
          multiple
          collapse-tags
          @change="handleBatchSetPlat"
          placeholder="批量设置售卖平台"
        >
          <el-option
            v-for="item in salesPlatformList"
            :key="item.salePlatCode"
            :label="item.salePlatName"
            :value="item.salePlatCode">
          </el-option>
        </el-select>
        <el-button @click="handleBatchSetSaleArea">销售区域</el-button>
        <el-button @click="concatDialog(1, 0)">关联品类</el-button>
        <el-button @click="concatDialog(1, 2)">关联品牌</el-button>
        <el-button @click="concatDialog(1, 5)">材质</el-button>
        <el-button @click="concatDialog(1, 'series')">系列</el-button>
        <el-button @click="handleCheckSameBrand">一键勾选相同品牌</el-button>
        <el-button @click="concatDialog(1, 9)">归类名称</el-button>
        <el-button @click="handleCheckSameCategory">一键勾选相同分类</el-button>
      </el-row>
      <div>
        <pl-table
          ref="plTable"
          use-virtual
          v-loading="loading"
          :height="height"
          :data="dataTable"
          :excess-rows="50"
          :row-height="49"
          :row-class-name="tableRowClass"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ textAlign: 'center' }"
          :cell-style="{ textAlign: 'center' }"
        >
          <pl-table-column type="selection" width="55" fixed />
          <pl-table-column
            v-for="item in tableColumns"
            :prop="item.prokey"
            :label="item.proname"
            :width="item.width || 120"
            :key="item.ind"
          >
            <template v-if="item.required" slot="header">
              <span class="must_icon">*</span><span>{{ item.proname }}</span>
            </template>
            <template slot-scope="scope">
              <span v-if="item.type == 'errorTip'">
                <el-tooltip class="item" effect="dark" :content="scope.row[item.prokey]" placement="top-start">
                  <div class="costom_tooltip">{{ scope.row[item.prokey] }}</div>
                </el-tooltip>
              </span>
              <span v-if="item.type == 'diff'">
                <template :title="scope.row[item.prokey]">
                  <span v-if="scope.row.productNameType == 1">{{ scope.row[item.prokey] }}</span>
                  <el-input
                    v-else
                    v-model="scope.row[item.prokey]"
                    :maxlength="item.maxlength"
                    :show-word-limit="item.maxlength ? true : false"
                    :title="scope.row[item.prokey]"
                  ></el-input>
                </template>
              </span>
              <span v-if="item.type === 0" class="td_div">
                <template :title="scope.row[item.prokey]">
                  <span v-if="item.prokey == 'productNameType'">{{ scope.row[item.prokey] == 1 ? '否' : '是'}}</span>
                  <span v-else :title="scope.row[item.prokey]">{{ scope.row[item.prokey] }}</span>
                </template>
              </span>
              <span v-if="item.type === 1">
                <template>
                  <el-input
                    v-if="item.disabled"
                    v-model="scope.row[item.prokey]"
                    :disabled="true"
                    :title="scope.row[item.prokey]"
                    @keyup.native="handleMoveFocus($event)"
                  ></el-input>
                  <el-input
                    :key="item.prokey + '_' + scope.$index"
                    v-else-if="item.isNum"
                    v-model="scope.row[item.prokey]"
                    :title="scope.row[item.prokey]"
                    @change="(val) => {checkNum(val, item.prokey, scope.$index);}"
                    @keyup.native="handleMoveFocus($event)"
                  ></el-input>
                  <el-input
                    :key="item.prokey + '_' + scope.$index"
                    v-else
                    v-model="scope.row[item.prokey]"
                    :title="scope.row[item.prokey]"
                    :maxlength="item.maxlength"
                    :show-word-limit="item.maxlength ? true : false"
                    @keyup.native="handleMoveFocus($event)"
                  ></el-input>
                  <em
                    class="err_msg"
                    v-if=" dataTableError[scope.$index] && dataTableError[scope.$index][item.prokey]"
                    >{{ dataTableError[scope.$index][item.prokey] }}</em
                  >
                </template>
              </span>
              <span v-if="item.type === 2">
                <el-input
                  placeholder=""
                  :key="item.prokey + '_' + scope.$index"
                  suffix-icon="el-icon-search"
                  @focus="concatDialog(0, item.sel, item.prokey, scope.$index, scope.row)"
                  v-model="scope.row[item.prokey]"
                  :title="scope.row[item.prokey]"
                >
                </el-input>
                <em
                  class="err_msg"
                  v-if="dataTableError[scope.$index] && dataTableError[scope.$index][item.prokey]"
                  >{{ dataTableError[scope.$index][item.prokey] }}</em
                >
              </span>
              <span v-if="item.type === 3">
                <template v-if="item.prokey === 'canCustom'">
                  <el-select
                    v-model="scope.row[item.prokey]"
                    placeholder="请选择"
                  >
                    <el-option value="1" label="是">是</el-option>
                    <el-option value="2" label="否">否</el-option>
                  </el-select>
                </template>
                <template v-if="item.prokey === 'saleResType'">
                  <el-select
                    v-model="scope.row[item.prokey]"
                    placeholder="请选择"
                  >
                    <el-option value="1" label="不低于起售量">不低于起售量</el-option>
                    <el-option value="2" label="起售量整数倍">起售量整数倍</el-option>
                  </el-select>
                </template>
                <template v-if="item.prokey === 'salePlatCodes'">
                  <el-select v-model="scope.row[item.prokey]" multiple collapse-tags>
                    <el-option
                      v-for="item in salesPlatformList"
                      :key="item.salePlatCode"
                      :label="item.salePlatName"
                      :value="item.salePlatCode">
                    </el-option>
                  </el-select>
                </template>
                <template v-if="item.prokey === 'seriesUuid'">
                  <el-select
                    v-model="scope.row[item.prokey]"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in scope.row.seriesInfoVos || []"
                      :key="item.seriesUuid"
                      :label="item.series"
                      :value="item.seriesUuid"
                    />
                  </el-select>
                </template>
                <template v-if="item.prokey === 'classificationName'">
                  <el-select
                    v-if="scope.row.classificationDTOS && scope.row.classificationDTOS.length > 1"
                    v-model="scope.row.classificationUuid"
                    placeholder="请选择"
                    @change="(val) => { handleClassificationChange(val, scope.row) }"
                  >
                    <el-option
                      v-for="item in scope.row.classificationDTOS || []"
                      :key="item.uuid"
                      :label="item.classificationName"
                      :value="item.uuid"
                    />
                  </el-select>
                  <span v-else :title="scope.row[item.prokey]">{{ scope.row[item.prokey] }}</span>
                </template>
              </span>
              <span v-if="item.type === 4">
                <el-input
                  :key="item.prokey + '_' + scope.$index"
                  v-model="scope.row[item.prokey]"
                  :title="scope.row[item.prokey]"
                  :maxlength="item.maxlength"
                  :show-word-limit="item.maxlength ? true : false"
                  @keyup.native="handleMoveFocus($event)"
                  @blur="handleOtherBrandInfo(scope.$index)"
                ></el-input>
              </span>
            </template>
          </pl-table-column>
          <pl-table-column
            fixed="right"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button @click="handleDelete(scope.row)" type="text" size="small">取消修改</el-button>
            </template>
          </pl-table-column>
        </pl-table>
      </div>
    </el-card>
    <el-dialog
      v-dialogDrag
      :title="dialogTit"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
    >
      <CategorySelect
        v-if="curConcatType == 0"
        @submitConcat="submitConcat"
        @cancelConcat="closeConcat"
      />
      <BrandSelect
        v-if="curConcatType == 2"
        @submitConcat="submitConcat"
        @cancelConcat="closeConcat"
      />
      <UnitSelect
        v-if="curConcatType == 3"
        @submitConcat="submitConcat"
        @cancelConcat="closeConcat"
      />
      <MaterialSelect
        v-if="curConcatType == 5"
        @submitConcat="submitConcat"
        @cancelConcat="closeConcat"
      />
    </el-dialog>
    <SalesAreaDialog
      :visible.sync="dialogVisible.salesArea"
      :cityList="cityList"
      :selectCitys="selectCitys"
      @getSaleAreas="getSaleAreas"
    />
    <!-- 关联品牌弹框 -->
    <SelectBrandAndSeries
      :visible.sync="associateBrand.visible"
      @update="updateBrandAndSeriesInfo"
    />
    <!-- 系列弹框 -->
    <BatchSetSeries
      :visible.sync="setSeries.visible"
      :brandUuid="setSeries.brandUuid"
      @update="updateSeriesInfo"
    />
    <!-- 归类弹框 -->
    <BatchSetClassification
      :visible.sync="classificationVisible"
      :classificationDTOS="classificationOptions"
      @update="updateClassificationInfo"
    />
  </div>
</template>

<script>
import CategorySelect from '../addCode/categorySelect';
import BrandSelect from '../addCode/brandSelect';
import UnitSelect from '../addCode/unitSelect';
import MaterialSelect from '../addCode/materialSelect';
import SalesAreaDialog from '@/components/SalesAreaDialog';
import SelectBrandAndSeries from '../components/SelectBrandAndSeries';
import BatchSetSeries from '../components/BatchSetSeries';
import BatchSetClassification from '../components/BatchSetClassification';
import parameConfig from './constants/add';
import { PRODUCT_NAME_TYPE } from './constants';
import {
  queryDetailByUuidsService, // 批量修改详情
  editSubmitService, // 提交
  exportSkuListForEditService
} from '@/api/commodity/temporaryPurchasingGoods/temporaryPurchaseGoods';
import {
  querySalePlatAndSaleAreasService,
  getSeriesByBrandUuidService
} from '@/api/public'; // 获取售卖平台及销售区域
import { getByBrandNameService } from '@api/basics/brandManage/brandManage';
import { isResponseSuccess, createExcelByExport, generateUuid } from '@/utils/bizUtils';
import { COMMON_COMP_CONFIGS } from '../latentProduct/constants/common';

export default {
  name: 'temporaryAddCode',
  components: {
    CategorySelect,
    BrandSelect,
    UnitSelect,
    MaterialSelect,
    SalesAreaDialog,
    SelectBrandAndSeries,
    BatchSetSeries,
    BatchSetClassification
  },
  data () {
    return {
      cityList: [],
      selectCitys: [],
      salesPlatformList: [], // 售卖平台下拉数据
      submitBtnLoading: false,
      PRODUCT_NAME_TYPE,
      formData: {
        productNameType: '', // 自定义商品名称 1-否，2-是
        salePlatCodes: [], // 售卖平台
      },
      loading: false,
      btnLoadings: {
        import: false,
        export: false,
      },
      dialogTableVisible: false,
      height: 0,
      dialogTitList: [
        '关联四级类',
        '关联SPU',
        '关联品牌',
        '关联单位',
        '关联库房',
        '批量设置材质'
      ],
      dialogTit: '关联四级类',
      curConcatType: 0,
      // 表格列数据
      tableColumns: _.cloneDeep(parameConfig.EDIT_TABLE_COLUMN),
      // 表格数据
      dataTable: [],
      // 错误数据提示
      dataTableError: [
        {
          y: '输入错误',
          x: '格式错误'
        }
      ],
      // 当前选中的商品
      selectedProduct: [],
      // 当前选中行的索引
      selectedIndList: [],
      // 当前操作是单行，还是批量
      isMultiple: 0,
      // 如果为单行操作时，当前行的索引
      concatInd: 0,
      // 当前操作的key
      concatKey: '',
      categoryUuid: '', // spu关联筛选时，当前分类id，如果有则传，没有不传
      dialogkf: false,
      type: '', // 1代表临采新增页面过来的
      addTemporaryFlag: false, // 临采新增页面添加按钮
      temporaryInd: 0, // 新增标识
      // 根据计量单位数量小数位默认“0时为1,1时为0.1,2时为0.01,3时为0.001”
      saleMinMap: {
        0: 1,
        1: 0.1,
        2: 0.01,
        3: 0.001,
      },
      uuids: [], // 商品id集合
      dialogVisible: {
        salesArea: false,
      },
      isBatchUpdate: false,
      uploadData: {},
      associateBrand: { ...COMMON_COMP_CONFIGS },
      setSeries: {
        ...COMMON_COMP_CONFIGS,
        brandUuid: '',
      },
      classificationVisible: false,
      classificationOptions: [],
    };
  },
  computed: {
    selectedProductIds () {
      return this.selectedProduct.map(item => item.uuid)
    }
  },
  created () {
    let screenHeight = document.body.clientHeight;
    this.height = screenHeight - 320;
    window.onresize = () => {
      let screenHeight = document.body.clientHeight;
      this.height = screenHeight - 320;
    };
  },
  mounted () {
    this.initPageByType()
    this.querySalePlatAndSaleAreas()
  },
  methods: {
    // 更新品牌系列信息
    updateBrandAndSeriesInfo (info) {
      this.dataChange(info)
    },
    // 更新系列信息
    updateSeriesInfo (info) {
      this.dataChange(info)
    },
    // 系列
    handleSeries (selection) {
      const brandUuid = selection[0].brandUuid
      if (!brandUuid) return this.$message.warning('品牌Id不能为空')
      const isAllSameBrand = selection.every(item => item.brandUuid == brandUuid)
      if (!isAllSameBrand) return this.$message.warning('请勾选相同品牌的商品进行系列设置')
      this.setSeries.brandUuid = brandUuid
      this.setSeries.open()
    },
    // 一键勾选相同品牌
    handleCheckSameBrand () {
      if (!this.selectedProduct.length || this.selectedProduct.length == 0) {
        return this.$message.warning('请勾选商品后进行操作');
      }
      const brandUuid = this.selectedProduct[0].brandUuid
      const isAllSameBrand = this.selectedProduct.every(item => item.brandUuid == brandUuid)
      if (!isAllSameBrand) return this.$message.warning('不支持勾选多个品牌进行设置')
      this.dataTable.forEach(item => {
        if (item.brandUuid != brandUuid) return
        this.$nextTick(() => {
          this.$refs.plTable.$refs.singleTable.toggleRowSelection(item, true)
        })
      })
    },
    // 更新归类信息
    updateClassificationInfo (info) {
      this.dataChange(info)
    },
    // 归类名称
    handleSetClassification (selection) {
      const categoryUuid = selection[0].categoryUuid
      if (!categoryUuid) return this.$message.warning('分类不能为空')
      const isAllSame = selection.every(item => item.categoryUuid == categoryUuid)
      if (!isAllSame) return this.$message.warning('请勾选相同分类的商品进行归类设置')
      this.classificationOptions = selection[0].classificationDTOS
      console.log(this.classificationOptions)
      this.classificationVisible = true
    },
    // 一键勾选相同品类
    handleCheckSameCategory () {
      if (!this.selectedProduct.length || this.selectedProduct.length == 0) {
        return this.$message.warning('请勾选商品后进行操作');
      }
      const categoryUuid = this.selectedProduct[0].categoryUuid
      const isAllSame = this.selectedProduct.every(item => item.categoryUuid == categoryUuid)
      if (!isAllSame) return this.$message.warning('不支持勾选多个分类进行设置')
      this.dataTable.forEach(item => {
        if (item.categoryUuid != categoryUuid) return
        this.$nextTick(() => {
          this.$refs.plTable.$refs.singleTable.toggleRowSelection(item, true)
        })
      })
    },
    // 导出模板
    async handleExportTemplate () {
      if (!this.formData.productNameType) {
        return this.$message.warning('请选择是否自定义商品名称，否则不能导出')
      }
      const uuid = generateUuid()
      const data = {
        productNameType: this.formData.productNameType,
        uuids: this.dataTable.length ? this.dataTable.map(item => item.uuid) : [],
        uuid
      }
      const loadingFn = state => { this.btnLoadings.export = state };
      const res = await exportSkuListForEditService(data, loadingFn);
      createExcelByExport({ res, excelTitle: `线索商品编辑模板_${uuid}` });
    },
    // 点击导入
    handleImport () {
      this.uploadData = {
        productNameType: this.formData.productNameType
      }
    },
    beforeFileUpload (file) {
      if (!this.formData.productNameType) {
        this.$message.warning('请选择是否自定义商品名称')
        return false;
      }
      this.btnLoadings.import = true;
    },
    uploadSuccess (res) {
      this.btnLoadings.import = false;
      if (isResponseSuccess(res)) {
        this.$message.success('导入成功')
        this.dataTable = res.retData;
        this.dataTable.forEach((item, index) => {
          item.ind = index;
        })
      } else {
        this.$message.error(res.retMessage || '模板导入异常');
      }
    },
    uploadError (file) {
      this.btnLoadings.import = false;
      this.$message.error('模板导入异常');
    },
    // 初始化页面数据
    initPageByType () {
      const { uuids } = this.$route.params;
      if (!uuids) {
        return this.hanldeGoBack()
      }
      this.uuids = uuids;
      this.queryDetailByUuids()
    },
    // 获取详情
    async queryDetailByUuids () {
      const { retData } = await queryDetailByUuidsService(this.uuids, state => { this.loading = state });
      if (retData) {
        this.dataTable = retData || [];
        this.dataTable.forEach((item, index) => {
          item.ind = index;
        })
      }
    },
    // 获取售卖平台及销售区域
    async querySalePlatAndSaleAreas () {
      const data = {};
      const res = await querySalePlatAndSaleAreasService(data, state => { this.loading = state });
      if (res) {
        const { retData } = res;
        this.cityList = retData.saleAreaList || [];
        this.salesPlatformList = retData.salePlatList || [];
      }
    },
    // 获取系列
    async getSeriesByBrandUuid (brandUuid) {
      const res = await getSeriesByBrandUuidService({ brandUuid }, state => { this.loading = state });
      if (res) {
        const { retData } = res;
        return retData;
      }
    },
    // 提交
    async handleSubmitAction () {
      if (!this.dataTable.length) {
        return this.$message.error('列表数据不能为空');
      }
      const res = await editSubmitService(this.dataTable, state => { this.submitBtnLoading = state });
      if (res) {
        if (res.retData && res.retData.hasErrorMsg) {
          this.$alert('存在异常原因，无法提交单据，请在详情页中查看具体原因', '提交错误提示', {
            confirmButtonText: '确定',
            type: 'warning',
          });
          if (this.tableColumns.every(item => item.prokey != 'errorMsg')) {
            this.tableColumns.unshift({
              prokey: 'errorMsg',
              proname: '异常原因',
              type: 'errorTip',
              width: 100
            })
          }
          this.dataTable = res.retData.data;
          this.dataTable.forEach((item, index) => {
            item.ind = index;
          })
        } else {
          this.$message.success('修改成功')
          this.$router.go(-1)
        }
      }
    },

    async handleOtherBrandInfo (index) {
      if (!this.dataTable[index].otherBrandName) {
        return;
      }
      this.dataTable[index].otherBrandName = this.dataTable[index].otherBrandName.trim();
      if (!this.dataTable[index].otherBrandName) {
        return;
      }
      const res = await getByBrandNameService(
        this.dataTable[index].otherBrandName,
        state => { this.loading = state }
      );
      const ret = res?.retData
      if (ret) {
        this.dataTable[index].brandName = ret.brandName;
        this.dataTable[index].brandUuid = ret.uuid;
        this.dataTable[index].otherBrandName = '';
      }
    },

    // 选择自定义商品名称
    handleProductNameTypeSelect (val) {
      this.dataTable.forEach(item => {
        item.productNameType = val
      });
    },
    // 批量设置售卖平台
    handleBatchSetPlat (val) {
      this.dataTable.forEach(item => {
        if (this.selectedProductIds.includes(item.uuid)) {
          item.salePlatCodes = val
        }
      });
    },

    // 批量设置销售区域
    handleBatchSetSaleArea () {
      if (this.selectedProductIds.length === 0) {
        return this.$message.warning('请选择商品！')
      }
      this.selectCitys = []
      this.isBatchUpdate = true;
      this.dialogVisible.salesArea = true;
    },

    // 删除
    handleDelete (row) {
      this.$confirm('确定取消修改吗？', '取消修改', {
        type: 'warning',
      }).then(() => {
        this.dataTable = this.dataTable.filter(item => item.uuid != row.uuid)
      }).catch(() => {});
    },
    tableRowClass () {
      return 'tem_row';
    },
    // 表格勾选
    handleSelectionChange (val) {
      this.selectedProduct = val;
    },
    /**
     *isMultiple ：multiple时为true批量操作，其它单品
     *type: 0分类，1spu,2品牌，3单位，4仓库
     *itemkey:当前操作的key,仓库多个时用
     *curInd:单品时的索引
     * **/
    concatDialog (isMultiple, type, itemkey, curInd, row) {
      this.isMultiple = isMultiple;
      if (isMultiple && !this.selectedProduct.length) {
        return this.$message.error('请选择商品！');
      }
      if (!isMultiple) {
        this.concatInd = curInd;
        // eslint-disable-next-line no-unused-expressions
        type == 1 ? (this.categoryUuid = this.dataTable[curInd].categoryUuid ? this.dataTable[curInd].categoryUuid : '') : false;
      }
      if (itemkey) {
        this.concatKey = itemkey
      }
      this.curConcatType = type;
      if (type == '2') { // 关联品牌
        return this.associateBrand.open()
      }
      if (type == 'series') { // 设置系列
        return this.handleSeries(this.selectedProduct)
      }
      if (type == 9) { // 设置归类名称
        return this.handleSetClassification(this.selectedProduct)
      }
      if (type == 6) {
        this.selectCitys = row.saleAreaCodes
        this.isBatchUpdate = false;
        this.dialogVisible.salesArea = true;
      } else {
        this.dialogTit = this.dialogTitList[Number(type)];
        this.dialogTableVisible = true;
      }
    },
    submitConcat (val) {
      this.dialogTableVisible = false;
      this.dataChange(val);
    },
    dataChange (valObj) {
      console.log('valObj: ' + JSON.stringify(valObj));
      let curIndList = null;
      if (this.isMultiple) {
        curIndList = this.selectedProduct.map((item) => {
          return item.ind;
        });
      } else {
        curIndList = [this.concatInd];
      }
      if (this.curConcatType === 3) {
        // 选择计量单位带出最小起售量
        this.dataTable.forEach((item, index) => {
          if (curIndList.includes(item.ind)) {
            if (!item.saleMin || Object.values(this.saleMinMap).includes(item.saleMin)) {
              item.saleMin = this.saleMinMap[valObj.decimalPlaces];
            }
            Object.assign(this.dataTable[index], valObj);
          }
        })
      } else if (this.curConcatType === 0) {
        // classificationDTOS
        this.dataTable.forEach((item, index) => {
          if (curIndList.includes(item.ind)) {
            const classificationObj = {
              ...valObj,
              uuid: valObj.classificationUuid
            }
            item.classificationDTOS = [classificationObj];
            Object.assign(this.dataTable[index], valObj);
          }
        })
      } else {
        for (let i = 0; i < curIndList.length; i++) {
          let curKk = curIndList[i];
          Object.assign(this.dataTable[curKk], valObj);
        }
      }
    },
    // 获取销售区域
    getSaleAreas (data) {
      const saleAreaStr = this.cityList.filter(item => data.includes(item.areaCode)).map(item => item.shortName).join(',')
      if (this.isBatchUpdate) {
        this.dataTable.forEach(item => {
          if (this.selectedProductIds.includes(item.uuid)) {
            item.saleAreaStr = saleAreaStr
            item.saleAreaCodes = data
          }
        });
      } else {
        this.dataTable[this.concatInd].saleAreaStr = saleAreaStr
        this.dataTable[this.concatInd].saleAreaCodes = data
      }
    },
    // 归类选择
    handleClassificationChange (val, row) {
      const selectItem = row.classificationDTOS.find(item => item.uuid == val)
      const {
        classificationName,
        uuid,
        taxCateName,
        taxCateNo,
        taxRate
      } = selectItem
      row.classificationName = classificationName
      row.classificationUuid = uuid
      row.taxCateName = taxCateName
      row.taxCateNo = taxCateNo
      row.taxRate = taxRate
    },
    closeConcat () {
      this.dialogTableVisible = false;
    },
    hanldeGoBack () {
      this.$router.push({ name: 'temporaryManageList' })
    },
    computedVolume (edge1, edge2, edge3) {
      if (edge1 && edge2 && edge3) {
        let val = (edge1 * edge2 * edge3) / 1000000;

        val = Number(val).toFixed(6);
        if (val <= 0) {
          val = 0.000001;
        }
        return val;
      } else {
        return '';
      }
    },
    checkNum (tVal, key, ind) {
      let curVal = tVal.replace(/[^0-9.]/g, '');
      if (!curVal) {
        this.dataTable[ind][key] = curVal;
        return;
      }
      if (
        key === 'purchasePrice' ||
        key === 'costPrice'
      ) {
        curVal = this.toFixedFn(Number(curVal), 3);
      } else {
        curVal = this.toFixedFn(Number(curVal), 2);
      }
      this.dataTable[ind][key] = Number(curVal);
      if (key === 'edge1' || key === 'edge2' || key === 'edge3') {
        this.dataTable[ind].volume = this.computedVolume(
          this.dataTable[ind].edge1,
          this.dataTable[ind].edge2,
          this.dataTable[ind].edge3
        );
      }
    },
    toFixedFn (num, toNum) {
      let def = 100;
      if (toNum == 3) {
        def = 1000;
      }
      if (toNum == 6) {
        def = 1000000;
      }
      if (num > 0) {
        return Math.round(num * def) / def;
      }
      return 0;
    },
    handleMoveFocus (event) {
      let curel = document.activeElement; // 当前input元素
      let curtTd = curel.parentElement.parentElement.parentElement.parentElement;
      let curcellIndex = curtTd.cellIndex; // 当前元素行单元格索引
      let curtTr = curtTd.parentElement; // 当前tr
      let curRowIndex = curtTr.sectionRowIndex; // 当前元素行的索引；
      let curtbody = curtTr.parentElement.children; // 当前tbody内容的整个表单
      // 向上
      if (event.keyCode == 38) {
        if (curRowIndex - 1 >= 0) {
          curtbody[curRowIndex - 1].children[curcellIndex].querySelector('.el-input__inner').focus()
        }
      }
      // 向下
      if (event.keyCode == 40) {
        if (curRowIndex + 1 !== curtbody.length) {
          curtbody[curRowIndex + 1].children[curcellIndex].querySelector('.el-input__inner').focus()
        }
      }
      // 向右
      if (event.keyCode === 39) {
        const rightInput = curtTr.children[curcellIndex + 1].querySelector('.el-input__inner');
        if (rightInput) {
          rightInput.focus()
        }
      }
      // 向左
      if (event.keyCode === 37) {
        const leftInput = curtTr.children[curcellIndex - 1].querySelector('.el-input__inner');
        if (leftInput) {
          leftInput.focus()
        }
      }
    },
  },
  directives: {
    dialogDrag: {
      bind (el, binding, vnode, oldVnode) {
        const dialogHeaderEl = el.querySelector('.el-dialog__header');
        const dragDom = el.querySelector('.el-dialog');
        dialogHeaderEl.style.cssText += ';cursor:move;';
        dragDom.style.cssText += ';top:0px;';
        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
        const sty = (function () {
          if (window.document.currentStyle) {
            return (dom, attr) => dom.currentStyle[attr];
          } else {
            return (dom, attr) => getComputedStyle(dom, false)[attr];
          }
        })();
        dialogHeaderEl.onmousedown = (e) => {
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX - dialogHeaderEl.offsetLeft;
          const disY = e.clientY - dialogHeaderEl.offsetTop;

          const screenWidth = document.body.clientWidth; // body当前宽度
          const screenHeight = document.documentElement.clientHeight; // 可见区域高度(应为body高度，可某些环境下无法获取)

          const dragDomWidth = dragDom.offsetWidth; // 对话框宽度
          const dragDomheight = dragDom.offsetHeight; // 对话框高度

          const minDragDomLeft = dragDom.offsetLeft;
          const maxDragDomLeft =
            screenWidth - dragDom.offsetLeft - dragDomWidth;

          const minDragDomTop = dragDom.offsetTop;
          const maxDragDomTop =
            screenHeight - dragDom.offsetTop - dragDomheight;
          // 获取到的值带px 正则匹配替换
          let styL = sty(dragDom, 'left');
          let styT = sty(dragDom, 'top');

          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (styL.includes('%')) {
            // eslint-disable-next-line no-useless-escape
            styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100);
            // eslint-disable-next-line no-useless-escape
            styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100);
          } else {
            styL = +styL.replace(/\px/g, '');
            styT = +styT.replace(/\px/g, '');
          }

          document.onmousemove = function (e) {
            // 通过事件委托，计算移动的距离
            let left = e.clientX - disX;
            let top = e.clientY - disY;

            // 边界处理
            if (-left > minDragDomLeft) {
              left = -minDragDomLeft;
            } else if (left > maxDragDomLeft) {
              left = maxDragDomLeft;
            }

            if (-top > minDragDomTop) {
              top = -minDragDomTop;
            } else if (top > maxDragDomTop) {
              top = maxDragDomTop;
            }

            // 移动当前元素
            dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
          };

          document.onmouseup = function (e) {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      }
    }
  }
};
</script>

<style lang="less" scoped>
.el-divider--horizontal {
  margin: 12px 0;
}
.card-title {
  margin-bottom: 3px;
}
.operating {
  margin-bottom: 10px;
  .el-select {
    width: 170px;
    margin-right: 10px;
  }
}
.srm_table_head {
  text-align: center;
}
.must_icon {
  color: red;
  margin: 0 5px;
}

.err_msg {
  position: absolute;
  left: 10px;
  bottom: -4px;
  font-style: normal;
  color: red;
}

.kf_radio .kf_radio_btn {
  margin: 10px 20px;
}
.el-table .pl-table-beyond {
  position: static;
}
.sale-area-input {
  width: 220px;
}
.el-select, .el-input {
  width: 90%;
}
.import-file {
  display: inline-block;
  margin: 0 10px;
}
</style>
